package com.warthur.jfinal.demo.interceptor;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.warthur.jfinal.demo.common.ErrorCode;
import com.warthur.jfinal.demo.common.HttpMethod;
import com.warthur.jfinal.demo.controller.BaseController;

/**
 * @author warthur
 * @date 2019/10/07
 */
public class Http {

    public static class GET implements Interceptor {
        @Override
        public void intercept(Invocation inv) {
            Http.intercept(inv, HttpMethod.GET);
        }
    }

    public static class POST implements Interceptor {
        @Override
        public void intercept(Invocation inv) {
            Http.intercept(inv, HttpMethod.POST);
        }
    }

    public static class PUT implements Interceptor {
        @Override
        public void intercept(Invocation inv) {
            Http.intercept(inv, HttpMethod.PUT);
        }
    }

    public static class DELETE implements Interceptor {
        @Override
        public void intercept(Invocation inv) {
            Http.intercept(inv, HttpMethod.DELETE);
        }
    }

    private static void intercept(Invocation inv, HttpMethod httpMethod) {
        BaseController controller = (BaseController) inv.getController();
        if (httpMethod.toString().equalsIgnoreCase(inv.getController().getRequest().getMethod())) {
            inv.invoke();
        } else {
            controller.renderError(400, ErrorCode.REQUEST_METHOD_ERROR);
        }
    }
}
